//
//  FeedbackVc.swift
//  Pods
//
//  Created by eme on 2017/4/6.
//
//

import UIKit
import UtilCore
import CommonCore
import RickonCore
import BrandonCore

class FeedbackVc: Base_Vc{
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var custom_TextView: UITextView!
    
    @IBOutlet weak var Custom_CollectionView: UICollectionView!
    
    @IBOutlet weak var commit_Button: UIButton!                     //提交按钮
    
    @IBOutlet weak var collectorHeight: NSLayoutConstraint!
    
    @IBOutlet weak var phone_Label: UILabel!                        //电话Label
    
    @IBOutlet weak var name_Label: UILabel!                         //姓名label
    
    @IBOutlet weak var LineView: UIView!                            //Line1
    
    @IBOutlet weak var Line2View: UIView!                           //line2
    
    @IBOutlet weak var Line3View: UIView!                           //line3
    
    @IBOutlet weak var left_NameLabel: UILabel!                     //姓名Label
    
    @IBOutlet weak var left_phoneLabel: UILabel!                    //电话label
    
    @IBOutlet weak var Feedback_leftLabel: UILabel!                 //反馈内容Label
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var qiniuVm:Qiniu_Vm?
    
    var imageArr = [String](){
        didSet{
            self.Custom_CollectionView.reloadData()
        }
    }
    var gtsm:shopMessageVm?
    
    var spModel:ShopMseeageModel?
    
    /****************************Storyboard 绑定方法区域****************************/
    @IBAction func CommitFK(_ sender: UIButton) {
        
        if self.custom_TextView.textColor == UIColor.black && self.custom_TextView.text != ""{
            if ischange(self.custom_TextView.text,length: 150) != true
            {
                self.view.toastErrorCode(100054006)
            }
            else
            {
                if let user = AppData.loginedUser{
                   let picurl = imageArr.joined(separator: ",")
                    let commitData:[String:String] = ["picurl":picurl,"feedbacksource":"1","feedbackstatus":"0","feedbackcommnet":self.custom_TextView.text,"appraiserid":"\(user.userid!)"]
                   self.gtsm?.submitFeedBack.onNext(JSONHelper.parseToJson(commitData as AnyObject) as String)
                }
            }
        }else{
            self.view.toastErrorCode(100054007)
        }
        
    }
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        LineView.backgroundColor = Theme.v.separate_Line
        Line2View.backgroundColor = Theme.v.separate_Line
        Line3View.backgroundColor = Theme.v.separate_Line
        phone_Label.normal_fontSize(16)
        name_Label.normal_fontSize(16)
        left_NameLabel.normal_fontSize(16)
        phone_Label.normal_fontSize(16)
        Feedback_leftLabel.normal_fontSize(16)
        custom_TextView.font = UIFont(name:Theme.font.light,size:14)
        commit_Button.titleLabel?.bold_fontSize(17)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if let str = AppData.loginedUser?.thrid{
            self.gtsm?.getShopMessage.onNext(str)
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setupCustom_TextView()
        self.setUpCustom_CollectionView()
        self.setUpCommitButton()
    }

    func setupCustom_TextView(){
        
        custom_TextView.layer.borderColor = Theme.sansa.buildPhone.textfield_Border.cgColor
        custom_TextView.layer.borderWidth = 1
        custom_TextView.delegate = self
    }
    func setUpCustom_CollectionView(){
        
        let MyLayout = UICollectionViewFlowLayout()
        let width = (self.custom_TextView.frame.width - 10 * 4)/4
        MyLayout.itemSize = CGSize(width: 64, height: 64)
        MyLayout.scrollDirection = UICollectionViewScrollDirection.vertical
        MyLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5)
        Custom_CollectionView.collectionViewLayout = MyLayout
        Custom_CollectionView.register(CameraImageCollectionViewCell.self, forCellWithReuseIdentifier: "cameraCell")
        Custom_CollectionView.register(MessageImageCollectionViewCell.self, forCellWithReuseIdentifier: "imageCell")
        Custom_CollectionView.delegate = self
        Custom_CollectionView.dataSource = self
        collectorHeight.constant = 4/4 * (width + 10)
        
    }
    func setUpHeight(){
        
        let width = (self.custom_TextView.frame.width - 10 * 4)/4
        
        if self.view.frame.width <= 320{
            
            if self.imageArr.count == 3{
                
                collectorHeight.constant = width + 20 + width + 20
                
            }else{
                
                collectorHeight.constant = width + 30
            }
        }
    }
    func setUpCommitButton(){
        commit_Button.layer.masksToBounds = true
        commit_Button.layer.cornerRadius = 4
        commit_Button.backgroundColor = UIColor.clear
        commit_Button.setBackgroundImage(Theme.btn.normal.getImage(), for: .normal)
        commit_Button.setBackgroundImage(Theme.btn.highlighted.getImage(), for: .highlighted)
        commit_Button.setBackgroundImage(Theme.btn.disabled.getImage(), for: .disabled)
    }
    func deleteImage(_ sender:UIButton){
        
        self.imageArr.remove(at: sender.tag)
    }
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        //-----------------------------------------
        //上传图片
        
        self.qiniuVm = Qiniu_Vm()
        self.qiniuVm?.uploadImageSuccess.subscribe(onNext:{[unowned self] splicenseurl in
            
            
            self.imageArr.append(splicenseurl)
            self.setUpHeight()
            
            }).addDisposableTo(disposeBag)
        
        
        self.qiniuVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.qiniuVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //-----------------------------------------
        //获取店铺信息
        
        self.gtsm = shopMessageVm()
        
        self.gtsm?.backMessage.subscribe(onNext:{ result in
            
            self.spModel = result
            self.name_Label.text = result.spcontact
            self.phone_Label.text = result.spmobile
            
            }).addDisposableTo(disposeBag)
        
        
        self.gtsm?.loading.bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        //======提交反馈
        self.gtsm?.submitBackDate.subscribe(onNext:{ result in
            if result != false{
                self.view.toastCompletion(UtilCore.alertmsg[100054008]!.msgtitle, completion: { _ in
                    _ = self.navigationController?.popViewController(animated: true)
                })
            }
        }).addDisposableTo(disposeBag)
        
        self.gtsm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
    }
}
extension FeedbackVc:UITextViewDelegate{
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if textView.textColor != UIColor.black
        {
            textView.text = ""
            textView.textColor = UIColor.black
            return true
        }
        else
        {
            return true
        }
    }
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text != ""
        {
            if ischange(textView.text,length: 150) != true
            {
                self.view.toast("最多输入150个字符")
            }
        }
        if textView.text == ""
        {
            textView.text = "欢迎您提出宝贵的意见或建议，您留下的每一个字都将用于改善我们的服务。"
            textView.textColor = UIColor(hex: "c7c7cd")
        }
    }
    func ischange(_ text:String,length:Int) -> Bool
    {
        let num:NSInteger = (text as NSString).length
        
        if num > length
        {
            return false
            
        }
        else
        {
            return true
        }
    }
}
extension FeedbackVc:UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.imageArr.count + 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if self.imageArr.count == indexPath.row{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cameraCell", for: indexPath) as! CameraImageCollectionViewCell
            cell.customImageView.image = UIImage(named: "camera", in: SansaCore.bundle, compatibleWith: nil)
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! MessageImageCollectionViewCell
            cell.deleteButton.tag = indexPath.row
            
            cell.deleteButton.addTarget(self, action: #selector(FeedbackVc.deleteImage(_:)), for: .touchUpInside)
            
            cell.customImageView.setUrlImage(self.imageArr[indexPath.row])
            return cell
        }
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch indexPath.row {
        case self.imageArr.count:
            if self.imageArr.count < 3{
                
                selectIcon()
                
            }else{
                self.view.toast("最多上传3张图片")
            }
            
        default:
            break
        }
    }
    //-----------------------------------
    ///改变头像
    func selectIcon()
    {
        let userIconAlert = UIAlertController(title: "请选择操作", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let chooseFromPhotoAlbum = UIAlertAction.init(title: "从相册选择", style: UIAlertActionStyle.default, handler: { UIAlertAction in
            self.ChooseFromPhotoAlbum()
        })
        
        let chooseFromCamera = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default,handler:{ UIAlertAction in
            self.ChooseFromCamera()
        })
        
        let canelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler: nil)
        
        userIconAlert.addAction(canelAction)
        userIconAlert.addAction(chooseFromCamera)
        userIconAlert.addAction(chooseFromPhotoAlbum)
        
        self.present(userIconAlert, animated: true, completion: nil)
        
    }
    
    //MARK:-
    //MARK:从相册选取图片
    func ChooseFromPhotoAlbum() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing = true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    //MARK:-
    //MARK:拍照
    func ChooseFromCamera() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing=true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    //编辑完成获取完成后的图片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获得编辑后的图片
        if let image = (info as NSDictionary).object(forKey: UIImagePickerControllerEditedImage) as? UIImage  {
            self.qiniuVm?.uploadImageSubject.onNext(image)
        }
        picker.dismiss(animated: true, completion: nil)
    }
}
